<template>
  <div class="auth-mask" v-if="isToLogin != null">
    <!-- 展示登录 -->
    <div class="form-box" v-if="isToLogin">
      <div class="head">
        <h1 class="title">登录</h1>
        <i class="iconfont icon-cha" @click="hide_mask()"></i>
      </div>
      <ValidationObserver ref="login_form">
        <ValidationProvider rules="required" name="用户名">
          <div class="username-wrapper" slot-scope="{ errors,classes }">
            <input
              type="text"
              class="username"
              :class="classes"
              placeholder="请输入用户名"
              v-model="login.username"
            />
            <p class="form_tips">{{ errors[0] }}</p>
          </div>
        </ValidationProvider>
        <ValidationProvider rules="required" name="密码">
          <div class="password-wrapper" slot-scope="{ errors,classes }">
            <input
              type="password"
              class="password"
              :class="classes"
              placeholder="请输入密码"
              v-model="login.password"
            />
            <p class="form_tips">{{ errors[0] }}</p>
          </div>
        </ValidationProvider>
      </ValidationObserver>

      <div class="login">
        <button @click="tologin()">登录</button>
      </div>
      <div class="tips">
        还没有账号？
        <span @click="reverse(true)">注册</span>
      </div>
    </div>

    <!-- 展示注册 -->
    <div class="form-box" v-if="!isToLogin">
      <div class="head">
        <h1 class="title">注册</h1>
        <i class="iconfont icon-cha" @click="hide_mask"></i>
      </div>
      <ValidationObserver ref="register_form">
        <ValidationProvider rules="required" name="用户名">
          <div class="username-wrapper" slot-scope="{ errors,classes }">
            <input
              type="text"
              class="username"
              :class="classes"
              placeholder="请输入用户名"
              v-model="register.username"
            />
            <p class="form_tips">{{ errors[0] }}</p>
          </div>
        </ValidationProvider>
        <ValidationProvider rules="required|email" name="邮箱">
          <div class="email-wrapper" slot-scope="{ errors,classes }">
            <input
              type="text"
              class="email"
              :class="classes"
              placeholder="请输入邮箱"
              v-model="register.email"
            />
            <p class="form_tips">{{ errors[0] }}</p>
          </div>
        </ValidationProvider>
        <ValidationProvider rules="required" name="密码">
          <div class="password-wrapper" slot-scope="{ errors,classes }">
            <input
              type="password"
              class="password"
              :class="classes"
              placeholder="请输入密码"
              v-model="register.password"
            />
            <p class="form_tips">{{ errors[0] }}</p>
          </div>
        </ValidationProvider>
      </ValidationObserver>
      <div class="login">
        <button @click="toregister()">注册</button>
      </div>
      <div class="tips">
        已有账号？
        <span @click="reverse(false)">登录</span>
      </div>
    </div>
  </div>
</template>

<script>
import jwt_decode from "jwt-decode";
import { ValidationProvider, ValidationObserver } from "vee-validate";
export default {
  name: "authbox",
  components: {
    ValidationProvider,
    ValidationObserver
  },
  data() {
    return {
      login: {
        username: "",
        password: ""
      },
      register: {
        username: "",
        email: "",
        password: ""
      }
    };
  },

  computed: {
    isToLogin() {
      return this.$store.getters.isToLogin;
    }
  },

  methods: {
    reverse(flag) {
      this.$store.dispatch("setIsToLogin", !flag);
      if (flag) {
        this.$refs.login_form.reset();
      } else {
        this.$refs.register_form.reset();
      }
    },
    tologin() {
      this.$refs.login_form.validate().then(res => {
        //   验证成功后
        if (res) {
          this.$axios
            .post("/login", {
              username: this.login.username,
              password: this.login.password
            })
            .then(res => {
              if (res.data.code == "0") {
                location.reload();
                const auth = res.data.data;
                localStorage.setItem("auth", auth);
                // 解析token
                const decode = jwt_decode(auth);
                this.$store.dispatch("setIsAuthenticated", true);
                this.$store.dispatch("setUser", decode);
              } else {
                this.$Message.error({
                  background: true,
                  content: res.data.msg,
                  duration: 2.5
                });
              }
            })
            .catch(err => {
              console.log(err);
              this.$Message.error({
                background: true,
                content: err.response.data.msg,
                duration: 2.5
              });
            });
        }
      });
    },

    toregister() {
      this.$refs.register_form.validate().then(res => {
        if (res) {
          this.$axios
            .post("/register", {
              username: this.register.username,
              email: this.register.email,
              password: this.register.password
            })
            .then(res => {
              if (res.data.code == "0") {
                location.reload();
                const auth = res.data.data;
                localStorage.setItem("auth", auth);
                // 解析token
                const decode = jwt_decode(auth);
                // console.log(decode);
                this.$store.dispatch("setIsAuthenticated", true);
                this.$store.dispatch("setUser", decode);
              } else {
                this.$Message.error({
                  background: true,
                  content: err.response.data.msg,
                  duration: 2.5
                });
              }
            })
            .catch(err => {
              console.log(err.response);
              // if (err.response.data.error) {
              //   this.$Message.error({
              //     background: true,
              //     content: err.response.data.error[0].message,
              //     duration: 2.5
              //   });
              // } else {
              //   this.$Message.error({
              //     background: true,
              //     content: "注册失败",
              //     duration: 2.5
              //   });
              // }
            });
        }
      });
    },
    hide_mask() {
      this.$store.dispatch("setIsToLogin", null);
      Object.assign(this.$data, this.$options.data());
    }
  }
};
</script>

<style lang='scss'>
.ivu-message {
  z-index: 5000 !important;
}

.ivu-notice {
  width: 10rem;
  .ivu-notice-notice {
    //   #b3d0ef
    // #33644b
    background-color: #b3d0ef;
  }
}
.auth-mask {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 2000;
  .form_tips {
    display: block;
    height: 1rem;
    font-size: 0.5rem;
    line-height: 1rem;
    margin: 0.3rem 0;
    padding: 0 0.5rem;
    color: red;
  }
  .form-box {
    background-color: #fff;
    padding: 1rem;
    width: 20rem;
    input {
      padding: 0 0.5rem;
      width: 100%;
      outline: none;
      border: 1px solid #ddd;
    }

    input.invalid {
      border: 1px solid #eb0600;
    }

    .head {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 1.5rem;
      .title {
        font-size: 20px;
      }
      i {
        font-size: 12px;
        color: #b3b3b3;
        cursor: pointer;
      }
      i:hover {
        color: #000;
      }
    }
    .username-wrapper {
      .username {
        height: 2.5rem;
        // margin-bottom: 1rem;
      }
    }
    .email-wrapper {
      .email {
        height: 2.5rem;
        // margin-bottom: 1rem;
      }
    }
    .password-wrapper {
      .password {
        height: 2.5rem;
        // margin-bottom: 1rem;
      }
    }
    .login {
      text-align: center;
      margin-bottom: 1rem;
      button {
        padding: 0.5rem 1.5rem;
        font-size: 0.9rem;
        border: none;
        outline: none;
        background-color: #1bb76e;
        color: #fff;
        cursor: pointer;
      }
      button:hover {
        background-color: #2ecc71;
      }
    }
    .tips {
      text-align: center;
      font-size: 0.8rem;
      span {
        color: #1bb76e;
        cursor: pointer;
      }
    }
  }
}
</style>